const { getUrlFileBuffer } = window.api

export function storageLocal() {
  return {
    setItem(key: string, value: any) {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      localStorage.setItem(key, value)
    },
    getItem(key: string): any {
      let value = localStorage.getItem(key)
      try {
        value = JSON.parse(value!)
      } catch (e) {
        // e
      }
      return value
    },
    removeItem(key: string) {
      localStorage.removeItem(key)
    },
    clear() {
      localStorage.clear()
    }
  }
}

function isValidHttpUrl(url: string) {
  try {
    const newUrl = new URL(url)
    return newUrl.protocol === 'http:' || newUrl.protocol === 'https:'
  } catch (err) {
    return false
  }
}

export async function urlAsBuffer(config: FileBufferParams) {
  if (!isValidHttpUrl(config.url)) {
    throw new Error(config.url + '不合法')
  }
  const buffer = await getUrlFileBuffer(config)
  return buffer
}

export async function urlAsBlobUrl(config: FileBufferParams) {
  const buffer = await urlAsBuffer(config)
  const blob = new Blob([buffer])
  const blobUrl = URL.createObjectURL(blob)
  return blobUrl
}

export function formatSeconds(seconds: number) {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  let str = secs.toString().padStart(2, '0')
  str = minutes.toString().padStart(2, '0') + ':' + str
  if (hours > 0) {
    str = hours.toString().padStart(2, '0') + ':' + str
  }

  return str
}

export function getRandomNumber(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}
